import Vue from 'vue'
import Vuex from 'vuex'
import { store as user } from './module/user/store'
import { store as movie } from './module/movie/store'
import { loginApi } from './module/user/api/api.js'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isLogin: localStorage.getItem('isLogin') || '2',
    token: localStorage.getItem('token') || '',
    version: '0.1.2'
  },
  modules: {
    user,
    movie
  },
  mutations: {
    CHANGE_LOGIN_STATUS: (state, { isLogin, token }) => { // 更改登录状态
      state.isLogin = isLogin
      state.token = token
    }
  },
  actions: {
    LOG_OUT: ({ commit, state }, params) => {
      localStorage.removeItem('isLogin')
      localStorage.removeItem('token')
      commit('CHANGE_LOGIN_STATUS', {
        isLogin: '2',
        token: ''
      })
    },
    DO_LOGIN: ({ commit, state, rootState }, params) => {
      return loginApi(params).then((data) => {
        if (data.code === 100) {
          // 将登录信息写入localStorage中
          localStorage.setItem('isLogin', '1')
          localStorage.setItem('token', data.result)
          return commit('CHANGE_LOGIN_STATUS', {
            isLogin: '1',
            token: data.result
          })
        }
      })
    }
  }
})
